import java.util.PriorityQueue;

class MyTimerTask2 implements Comparable<MyTimerTask2>{
private   Runnable runnable;
private long time;
public MyTimerTask2(Runnable runnable,long delay){
    this.runnable=runnable;
    this.time=System.currentTimeMillis()+delay;
}
public long getTime(){
    return  this.time;
}
public void run(){
    runnable.run();
}
@Override
    public int compareTo(MyTimerTask2 o) {
        return (int)(this.time-o.time);
    }
}
class MyTimer2{
    private Thread t=null;
   private PriorityQueue<MyTimerTask2>queue=new PriorityQueue<>();
   private Object locker1=new Object();
   public void cancel(){
       t.interrupt();
   }
   public void schedule(Runnable runnable,long delay){
       synchronized (locker1){
       MyTimerTask2 task2=new MyTimerTask2(runnable,delay);
       queue.offer(task2);
       locker1.notify();
       }

   }
   public MyTimer2(){
       this.t=new Thread(()->{
           while(!Thread.currentThread().isInterrupted()){
               try {
                   synchronized (locker1) {
                       while (queue.isEmpty()) {
                           locker1.wait();
                       }
                       MyTimerTask2 task2 = queue.peek();
                       if (System.currentTimeMillis() >= task2.getTime()) {
                           task2.run();
                           queue.poll();
                       } else {
                           locker1.wait(task2.getTime() - System.currentTimeMillis());
                       }

                   }
               }
               catch (InterruptedException e){
                   break;
               }
           }
       });
       t.start();
   }

}

public class TimerCounter2 {
    public static void main(String[] args) throws InterruptedException {
        MyTimer2 timer=new MyTimer2();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        },3000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 2000");
            }
        },2000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 1000");
            }
        },1000);
        Thread.sleep(5000);
        timer.cancel();
    }
}
